package com.cskaoyan.advice;

import com.cskaoyan.util.MyBatisUtil;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSession;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class TransactionAspect2 {

    @SneakyThrows
    public Object transactionAround(ProceedingJoinPoint joinPoint){
        Object target = joinPoint.getTarget();
        Field[] declaredFields = target.getClass().getDeclaredFields();
        SqlSession sqlSession = null;
        for (Field declaredField : declaredFields) {
            //是否是Mapper成员变量
            String name = declaredField.getName();
            if (name.endsWith("Mapper")) {
                sqlSession = MyBatisUtil.getSqlSession();
                Class<?> type = declaredField.getType();
                Object mapper = sqlSession.getMapper(type);//mapper代理对象
                declaredField.setAccessible(true);
                declaredField.set(target,mapper);
            }
        }
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            sqlSession.rollback();
            throwable.printStackTrace();
        }

        if (sqlSession != null) {
            sqlSession.commit();
            sqlSession.close();
        }
        return proceed;
    }
}
